#!/bin/bash
# WebSocket服务器监控脚本

LOG_FILE="/var/log/websocket_monitor.log"
SERVICE_NAME="patient-websocket.service"

# 检查服务状态
check_service() {
    if ! systemctl is-active --quiet $SERVICE_NAME; then
        echo "$(date): 服务未运行，正在重启..." >> $LOG_FILE
        systemctl restart $SERVICE_NAME
        sleep 5
        
        if systemctl is-active --quiet $SERVICE_NAME; then
            echo "$(date): 服务重启成功" >> $LOG_FILE
        else
            echo "$(date): 服务重启失败" >> $LOG_FILE
        fi
    fi
}

# 检查端口是否监听
check_port() {
    if ! netstat -tlnp | grep ":8080"; then
        echo "$(date): 端口8080未监听，重启服务..." >> $LOG_FILE
        systemctl restart $SERVICE_NAME
    fi
}

# 主循环
while true; do
    check_service
    check_port
    sleep 60  # 每分钟检查一次
done
